package com.sky.controller.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.util.Set;

@Component
public class TestController {

    private static final String ORDER_TIMEOUT_KEY = "order:timeout:zset";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 派单时调用，把订单ID和超时触发时间（时间戳）加入ZSET
     * @param orderId 订单ID
     * @param timeoutTimestamp 超时触发的时间戳（秒或毫秒）
     */
    public void addOrderToDelayQueue(String orderId, long timeoutTimestamp) {
        redisTemplate.opsForZSet().add(ORDER_TIMEOUT_KEY, orderId, timeoutTimestamp);
    }

    /**
     * 定时任务每秒执行一次，取出所有超时订单处理
     */
    @Scheduled(fixedRate = 1000)//频率：1000ms
    public void processTimeoutOrders() {
        long now = Instant.now().toEpochMilli();

        // 取出score <= now的所有订单ID，表示这些订单已超时
        Set<String> expiredOrderIds = redisTemplate.opsForZSet()
                .rangeByScore(ORDER_TIMEOUT_KEY, 0, now);

        if (expiredOrderIds == null || expiredOrderIds.isEmpty()) {
            return;
        }

        for (String orderId : expiredOrderIds) {
            //实现业务逻辑，修改订单状态、发短信等......
            Order order = new Order();
            order.setOrderId(orderId);
            order.setOrderstate("拒单");
            orderMapper.updateOrderState(order);

            //从redis移出
            redisTemplate.opsForZSet().remove(ORDER_TIMEOUT_KEY, orderId);

        }
    }
}